#coding=utf-8
import status,datetime
print datetime.datetime.now()

reverse_apps = ['song-jiang', 'wu-yong', 'lu-jun-yi', 'cai-jin', 'hua-rong', 'lu-zi-sen', 'wu-song', 'gong-sun-sen', 'guan-shen', 'hu-yan-zuo', 'lin-cong', 'li-yin', 'qin-min', 'zu-tong']
http_apps = ['cai-jin', 'hua-rong', 'lu-zi-sen', 'wu-song', 'gong-sun-sen', 'guan-sen', 'hu-yan-zuo', 'lin-cong', 'li-yin', 'qin-min', 'zu-tong', 'dong-pin','zang-qin', 'yang-zi', 'xu-nin', 'dai-zong']
reverse_port = '8001'
http_ports = ['8002', '8003', '8004', '8005']

def print_red(s):print '\033[0;31;48m%s\033[0m'%s

print_red('当前app进程运行情况:') 
result = status.check_running_proxy()
r = result['reverse']
print 'reverse:', r
hs = result['http']
print 'http:',
for h in hs:
    print '\t', h

#始终保证有一个reverse proxy app在正常运行
reverse_available = []
for a in reverse_apps:
    if status.check_connect(a, 'reverse'): reverse_available.append(a)

if not r:
    appid = reverse_available[0]
    status.start_proxy(appid, reverse_port, 'reverse')
elif r[0] not in reverse_available:
    status.stop_proxy(r[-1])
    appid = reverse_available[0]
    status.start_proxy(appid, reverse_port, 'reverse')
else:
    print 'reverse proxy %s works fine'%r[0]

#如果有没有被封http可用的app,start it 
http_available = []
for a in http_apps:
    if status.check_connect(a, 'http'): http_available.append(a)
print_red('http可用的app:')
print http_available

for h in hs:
    if h[0] not in http_available:
        status.stop_proxy(h[-1])
        
result = status.check_running_proxy()
hs = result['http']

http_running_ports = [h[-2] for h in hs]
not_use_ports = list(set(http_ports) - set(http_running_ports))
http_running_appids = [h[0] for h in hs]
for appid in http_available:
    if appid not in http_running_appids:
        print 'http可用未用的app:', appid
        if not_use_ports:
            port = not_use_ports.pop()
            status.start_proxy(appid, port, 'http')        
            print '\t开启http代理:%s --> %s'%(appid, port)
